package com.example.drive.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.drive.ContextHolder
import com.example.drive.bean.DrivingAnswerBean
import com.example.drive.bean.ResultBean

/**
 * 驾考题库数据库，两张表ResultBean和DrivingAnswerBean
 */
@Database(
    entities = [ResultBean::class, DrivingAnswerBean::class],
    version = 1,
    exportSchema = false
)
abstract class JZTKDataBase : RoomDatabase() {
    abstract fun getResultBeanDao(): ResultBeanDao

    abstract fun getDrivingAnswerBeanDao(): DrivingAnswerBeanDao

    companion object {
        private const val DB_NAME = "jztk.db"
        private const val defaultValue = "anyValue"
        private val MIGRATIONS = arrayOf(
            object : Migration(1, 2) {
                override fun migrate(database: SupportSQLiteDatabase) {
                    // 这里执行数据库升级操作
                    database.execSQL("ALTER TABLE Result ADD COLUMN anyField TEXT NOT NULL DEFAULT ($defaultValue)")
                    println("Migration 1 to 2")
                }
            },
            object : Migration(2, 3) {
                override fun migrate(database: SupportSQLiteDatabase) {
                    //
                    println("Migration 2 to 3")
                }
            }
        )

        private val resultBeanDataBase by lazy {
            Room.databaseBuilder(ContextHolder.context, JZTKDataBase::class.java, DB_NAME)
                .addMigrations(*MIGRATIONS)
                .build()
        }

        val resultBeanDao: ResultBeanDao by lazy {
            resultBeanDataBase.getResultBeanDao()
        }

        val drivingAnswerBeanDao: DrivingAnswerBeanDao by lazy {
            resultBeanDataBase.getDrivingAnswerBeanDao()
        }
    }
}